import * as StorageHelper from '../../utils/token-storage';
import _ from 'lodash';
import dayjs from 'dayjs';
let requestTimer = null;
let responseTimer = null;
let requestFlag = true;
let responseFlag = true;

function intercept(request) {
  request.interceptors.request.use(
    options => {
      // 获取子应用传入的bladeUrl
      let { bladeUrl } = window.yiautosConfig,
        { url } = options;
      // 接口域名请配置于各微应用 network/url-list.js 文件中
      if (!bladeUrl) {
        throw new Error('请配置接口请求域名');
      }
      // 拼接域名
      // bladeUrl规范示例：'http://api.test.itsmycar.cn/api/', 最后以 / 结尾, 若没有则会自动拼接上
      if (!/\/$/.test(bladeUrl)) {
        bladeUrl = `${bladeUrl}/`;
      }
      // 业务接口地址不已 / 开头, 若匹配到斜杆开头则会去除
      if (/^http|^https/.test(url)) {
        options.url = `${url}`;
      } else {
        if (/^\//.test(url)) {
          url = url.slice(1);
        }
        options.url = `${bladeUrl}${url}`;
      }
      const bladeToken = StorageHelper.getBladeToken();
      if (tokenExpireVerify()) {
        throw new Error('登录过期');
      }
      if (bladeToken) {
        // TODO 将BladeToken放入请求的header中
        options.headers['Blade-Auth'] = 'bearer ' + bladeToken;
        options.headers['Authorization'] = 'Basic c3dvcmQ6c3dvcmRfc2VjcmV0';
        options.headers['tenantId'] = '000000';
      }

      return options;
    },
    error => {
      console.log('请求发生错误 ==>', error);
      return Promise.reject(error);
    }
  );

  request.interceptors.response.use(
    response => {
      return response.data;
    },
    error => {
      console.log('响应发生错误 ==>', error, error.response);
      const errorMessage = _.get(error, 'response.data.msg', null);
      if (error.response && error.response.status === 401) {
        clearTimeout(responseTimer);
        if (responseFlag) {
          // console.log('发送401消息 ==>');
          responseFlag = false;
          window._EVENT_BUS && window._EVENT_BUS.$emit('MICRO_APP_401');
        }
        responseTimer = setTimeout(() => {
          responseFlag = true;
        }, 1000);
      }
      if (error.message === 'Network Error') {
        return Promise.reject(new Error('网络异常, 请检查您的网络连接!'));
      } else {
        return Promise.reject(errorMessage ? new Error(errorMessage) : error);
      }
    }
  );
}

function tokenExpireVerify() {
  // 判断是否有expire，nrp无，nrpqk有，若无则不走过期发消息逻辑兼容旧NRP
  // 判断是否存在token，且当前时间 < token过期时间 - 10min
  // 是发送消息'MICRO_APP_TOKEN_EXPIRE'通知主应用重新登录
  const bufferTime = 600000;
  const expire = StorageHelper.getBladeTokenExpire();
  const bladeToken = StorageHelper.getBladeToken();
  const currentTime = dayjs().valueOf();
  if (expire) {
    if (!Boolean(bladeToken && currentTime < expire - bufferTime)) {
      clearTimeout(requestTimer);
      if (requestFlag) {
        // console.log('发送token失效消息 ==>');
        requestFlag = false;
        window._EVENT_BUS && window._EVENT_BUS.$emit('MICRO_APP_TOKEN_EXPIRE');
      }
      requestTimer = setTimeout(() => {
        requestFlag = true;
      }, 1000);
      return true;
    }
    return false;
  } else {
    return false;
  }
}

export default intercept;
